// import * as XLSX from 'xlsx';
import { Button, Modal, Select, Table } from 'antd';
import { useState } from 'react'
import moment from 'moment';
import classes from './index.module.scss';
import { Com_Btns, Com_Map, List1, columns } from '../contant';


export const ComAdmin = () => {
  const user = '管理员1';
  const [comNumber, setComNumber] = useState('1');
  const [logs, setLogs] = useState([
    {
      key: '1',
      operator: user,
      operation: '修改配置',
      time: '2023-01-01 10:00:00',
      result: '成功'
    },
    {
      key: '2',
      operator: user,
      operation: '删除用户',
      time: '2023-01-01 11:00:00',
      result: '成功'
    },
    // ...更多日志
  ]);
  const handleClick = (item: any) => {
    setLogs([...logs, { key: `${logs.length + 1}`, operator: user, time: moment(new Date()).format('YYYY-MM-DD hh:mm:ss'), operation: `串口${comNumber}${item.name}`, result: item.click() }])
  }





  // 导出Excel
  //   const exportToExcel = () => {
  //     const ws = XLSX.utils.json_to_sheet(logs);
  //     const wb = XLSX.utils.book_new();
  //     XLSX.utils.book_append_sheet(wb, ws, "Logs");

  //     // 生成Excel文件并保存
  //     XLSX.writeFile(wb, 'logs.xlsx');
  //   };
  const exportToCSV = () => {
    let csvContent = "data:text/csv;charset=utf-8,";
    const headers = columns.map(column => column.title).join(',') + '\r\n';
    csvContent += headers;

    logs.forEach(logEntry => {
      const row = columns.map(column => logEntry[column.dataIndex]).join(',');
      csvContent += row + '\r\n';
    });

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', 'logs.csv');
    document.body.appendChild(link); // Required for FF

    link.click(); // This will download the CSV file
  };

  const BtnModule = (param: { item: any }) => {
    const { item } = param;
    return <Button className={classes['btn-com-collect']} type='primary' onClick={() => handleClick(item)}>
      {item.name}
    </Button>
  }

  return <>
    <div className={classes["container-com"]}>
      <div className={classes['com-admin']}>
        串口连接
        <Select style={{ width: '80px' }} options={List1} value={comNumber} onChange={(value) => setComNumber(value)}>
        </Select>
        {
          Object.values(Com_Map).map((item, index) => <BtnModule item={item} />)
        }
      </div>
    </div>
    <div className={classes.logModule}>
      {/* {lockId.map((str) => <div>{str}</div>)} */}
      <div>
        <Button onClick={exportToCSV} type="primary" style={{ marginBottom: 16 }}>
          导出到Excel
        </Button>
        <Table dataSource={logs} columns={columns} />
      </div>
    </div>
  </>

}